import 'package:flutter/material.dart';
import 'package:flustars/flustars.dart';
import 'package:flutter_picker/flutter_picker.dart';
import 'package:fluttertoast/fluttertoast.dart';

import 'MainLoading.dart';

// 控件部分

// 自定义导航栏中的返回按钮
AppBar getAppBar(BuildContext context, String str) {
  return AppBar(
    title: Text(str),
    elevation: 0,
    centerTitle: true,
    leading: IconButton(
      icon: Image.asset(
        "images/MainBackImage.png",
        height: 20,
        width: 20,
        color: Colors.black,
      ),
      onPressed: () => Navigator.of(context).pop(),
    ),
  );
}

Text mainText(
  String string,
  Color color,
  double size,
) {
  return Text(string,
      style: TextStyle(
        color: color,
        fontSize: setFontSize(size),
      ));
}

Widget mainBtnView(
  String title, {
  Color titleColor,
  Color backColor,
  Color lineColor,
  FontWeight fontWeight,
}) {
  return Container(
    decoration: BoxDecoration(
      color: backColor == null ? Color(0xFFFF7F27) : backColor,
      borderRadius: BorderRadius.all(Radius.circular(6)),
      border: Border.all(
        color: lineColor == null ? Color(0xFF333333) : lineColor,
        width: 2,
      ),
    ),
    child: Container(
      margin: EdgeInsets.fromLTRB(20, 8, 20, 8),
      child: Text(
        title,
        style: TextStyle(
          color: titleColor == null ? Color(0xFF333333) : titleColor,
          fontSize: setFontSize(30),
          fontWeight: fontWeight,
        ),
      ),
    ),
  );
}

Widget leftView(bool isSend) {
  return Container(
    padding: EdgeInsets.fromLTRB(
      setWidth(50),
      setHeight(30),
      setWidth(20),
      setHeight(30),
    ),
    child: Container(
      height: setHeight(56),
      width: setHeight(56),
      alignment: Alignment.center,
      child: isSend
          ? Image.asset("images/MainFaImage.png")
          : Image.asset("images/MainShouImage.png"),
    ),
  );
}

// 主要的方法

// 取消输入状态
removeFocus(BuildContext context) {
  FocusScope.of(context).requestFocus(FocusNode());
}

///保存本地
setData(String str01, str02) {
  SpUtil.getInstance();
  SpUtil.putString(str01, str02.toString());
}

// 本地获取
String getData(String str) {
  SpUtil.getInstance();
  return SpUtil.getString(str).toString();
}

Color maincolor = Color(0xFFFF8629);

// 一、不依赖context
// 系统AppBar高度
double appBarHeight = ScreenUtil.getInstance().appBarHeight;
// 屏幕宽
double screenWidth = ScreenUtil.getInstance().screenWidth;
// 屏幕高
double screenHeight = ScreenUtil.getInstance().screenHeight;
// 系统状态栏高度
double statusBarHeight = ScreenUtil.getInstance().statusBarHeight;
// BottomBar高度
double bottomBarHeight = ScreenUtil.getInstance().bottomBarHeight;
// 屏幕像素密度
double screenDensity = ScreenUtil.getInstance().screenDensity;

// 根据屏幕宽适配后尺寸
double setWidth(double width) {
  return ScreenUtil.getInstance().getWidth(width);
}

// 根据屏幕高适配后尺寸
double setHeight(double height) {
  return ScreenUtil.getInstance().getHeight(height);
}

// 根据屏幕宽适配后字体尺寸
double setFontSize(double fontSize) {
  return ScreenUtil.getInstance().getSp(fontSize);
}

// 根据屏幕宽适配后尺寸(输入px)
double setWidthPX(double width) {
  return ScreenUtil.getInstance().getWidthPx(width);
}

// 根据屏幕高适配后尺寸(输入px)
double setHeightPX(double width) {
  return ScreenUtil.getInstance().getHeightPx(width);
}

// // 二、依赖context
// // 屏幕宽
// double screenWidth = ScreenUtil.getScreenW(context);
// // 屏幕高
// double screenHeight = ScreenUtil.getScreenH(context);
// // 屏幕像素密度
// double screenDensity = ScreenUtil.getScreenDensity(context);
// // 系统状态栏高度
// double statusBarHeight = ScreenUtil.getStatusBarH(context);
// // BottomBar高度
// double bottomBarHeight = ScreenUtil.getBottomBarH(context);
// // 根据屏幕宽适配后尺寸
// double adapterW100 = ScreenUtil.getScaleW(context, 100);
// // 根据屏幕高适配后尺寸
// double adapterH100 = ScreenUtil.getScaleH(context, 100);
// // 根据屏幕宽适配后字体尺寸
// double adapterSp100 = ScreenUtil.getScaleSp(context, 100);
// // 屏幕方向
// Orientation orientation = ScreenUtil.getOrientation(context);

// 文字提示
void showToast(String text) {
  Fluttertoast.showToast(
    msg: text,
    toastLength: Toast.LENGTH_SHORT,
    gravity: ToastGravity.BOTTOM,
    timeInSecForIosWeb: 1,
    backgroundColor: maincolor,
    // textColor: Colors.white,
    fontSize: 16.0,
  );
}

// 手机号判断
bool isPhone(String str) {
  return new RegExp(
          '^((13[0-9])|(15[^4])|(166)|(17[0-8])|(18[0-9])|(19[8-9])|(147,145))\\d{8}\$')
      .hasMatch(str);
}

showLoading(BuildContext context) {
  showDialog(
    context: context,
    barrierDismissible: false,
    builder: (_) {
      return NetLoadingDialog(
        // dismissDialog: dismissLoading(context),
        outsideDismiss: false,
      );
    },
  );
}

dismissLoading(BuildContext context) {
  Navigator.pop(context);
}

///数组转字符串
String getStringWithList(List list) {
  List tempList = List();
  String str = '';
  list.forEach((f) {
    tempList.add(f.toString());
  });
  tempList.forEach((f) {
    if (str == '') {
      str = "$f";
    } else {
      str = "$str" "," "$f";
    }
  });

  return str;
}

// 截取字符前字段
String getCaption(obj) {
  var index = obj.lastIndexOf(".");
  obj = obj.substring(0, index);
  return obj;
  //  console.log(obj);
  // return obj;
}

///value: 文本内容；fontSize : 文字的大小；fontWeight：文字权重；maxWidth：文本框的最大宽度；maxLines：文本支持最大多少行
double textHeight(BuildContext context, String value, fontSize,
    FontWeight fontWeight, double maxWidth, int maxLines) {
  // value = filterText(value);
  TextPainter painter = TextPainter(

      ///AUTO：华为手机如果不指定locale的时候，该方法算出来的文字高度是比系统计算偏小的。
      locale: Localizations.localeOf(context, nullOk: true),
      maxLines: maxLines,
      textDirection: TextDirection.ltr,
      text: TextSpan(
          text: value,
          style: TextStyle(
            fontWeight: fontWeight,
            fontSize: fontSize,
          )));
  painter.layout(maxWidth: maxWidth);

  ///文字的宽度:painter.width
  return painter.height;
}

///value: 文本内容；fontSize : 文字的大小；fontWeight：文字权重；maxWidth：文本框的最大宽度；maxLines：文本支持最大多少行
double textWidth(
  BuildContext context,
  String value,
  fontSize,
) {
  TextPainter painter = TextPainter(
    locale: Localizations.localeOf(context, nullOk: true),
    textDirection: TextDirection.ltr,
    text: TextSpan(
      text: value,
      style: TextStyle(
        fontSize: fontSize,
      ),
    ),
  );
  painter.layout(maxWidth: double.infinity);

  ///文字的宽度:painter.width
  return painter.width;
}

const double kPickerHeight = 216.0;
const double kItemHeight = 40.0;
const Color kBtnColor = Color(0xFF323232); //50
const Color kTitleColor = Color(0xFF787878); //120
const double kTextFontSize = 17.0;

typedef StringClickCallback = void Function(int selectIndex, Object selectStr);
typedef ArrayClickCallback = void Function(
    List<int> selecteds, List<dynamic> strData);
typedef DateClickCallback = void Function(
    dynamic selectDateStr, dynamic selectDate);

enum DateType {
  YMD, // y, m, d
  YM, // y ,m
  YMD_HM, // y, m, d, hh, mm
  YMD_AP_HM, // y, m, d, ap, hh, mm
}

class JhPickerTool {
  /** 单列*/
  static void showStringPicker<T>(
    BuildContext context, {
    @required List<T> data,
    String title,
    int normalIndex,
    PickerDataAdapter adapter,
    @required StringClickCallback clickCallBack,
  }) {
    openModalPicker(context,
        adapter: adapter ?? PickerDataAdapter(pickerdata: data, isArray: false),
        clickCallBack: (Picker picker, List<int> selecteds) {
      //          print(picker.adapter.text);
      clickCallBack(selecteds[0], data[selecteds[0]]);
    }, selecteds: [normalIndex ?? 0], title: title);
  }

  /** 多列 */
  static void showArrayPicker<T>(
    BuildContext context, {
    @required List<T> data,
    String title,
    List<int> normalIndex,
    PickerDataAdapter adapter,
    @required ArrayClickCallback clickCallBack,
  }) {
    openModalPicker(context,
        adapter: adapter ?? PickerDataAdapter(pickerdata: data, isArray: true),
        clickCallBack: (Picker picker, List<int> selecteds) {
      clickCallBack(selecteds, picker.getSelectedValues());
    }, selecteds: normalIndex, title: title);
  }

  static void openModalPicker(
    BuildContext context, {
    @required PickerAdapter adapter,
    String title,
    List<int> selecteds,
    @required PickerConfirmCallback clickCallBack,
  }) {
    new Picker(
            columnPadding: EdgeInsets.only(right: 10),
            adapter: adapter,
            title: new Text(title ?? "请选择",
                style: TextStyle(color: kTitleColor, fontSize: kTextFontSize)),
            selecteds: selecteds,
            cancelText: '取消',
            confirmText: '确定',
            cancelTextStyle:
                TextStyle(color: kBtnColor, fontSize: kTextFontSize),
            confirmTextStyle:
                TextStyle(color: kBtnColor, fontSize: kTextFontSize),
            textAlign: TextAlign.right,
            itemExtent: kItemHeight,
            height: kPickerHeight,
            selectedTextStyle: TextStyle(color: Colors.black),
            onConfirm: clickCallBack)
        .showModal(context);
  }

//      /** 日期选择器*/
//       static void showDatePicker(
//           BuildContext context, {
//           DateType dateType,
//           String title,
//           DateTime maxValue,
//           DateTime minValue,
//           DateTime value,
//           DateTimePickerAdapter adapter,
//           @required DateClickCallback clickCallback,
//           }) {

//         int timeType;
//         if(dateType == DateType.YM){
//           timeType =  PickerDateTimeType.kYM;
//         }else if(dateType == DateType.YMD_HM){
//           timeType =  PickerDateTimeType.kYMDHM;
//         }else if(dateType == DateType.YMD_AP_HM){
//           timeType =  PickerDateTimeType.kYMD_AP_HM;
//         }else{
//           timeType =  PickerDateTimeType.kYMD;
//         }

//         openModalPicker(context,
//         adapter: adapter ??
//         DateTimePickerAdapter(
//         type: timeType,
//         isNumberMonth: true,
//         yearSuffix: "年",
//         monthSuffix: "月",
//         daySuffix: "日",
//         strAMPM: const["上午", "下午"],
//         maxValue: maxValue ,
//         minValue: minValue,
//         value: value ?? DateTime.now(),
//         ),
//         title: title,
//         clickCallBack:(Picker picker, List<int> selecteds){

//           var time = (picker.adapter as DateTimePickerAdapter).value;
//           var timeStr;
//           if(dateType == DateType.YM){
//             timeStr =time.year.toString()+"年"+time.month.toString()+"月";
//           }else if(dateType == DateType.YMD_HM){
//             timeStr =time.year.toString()+"年"+time.month.toString()+"月"+time.day.toString()+"日"+time.hour.toString()+"时"+time.minute.toString()+"分";
//           }else if(dateType == DateType.YMD_AP_HM){
//           var str = formatDate(time, [am])=="AM" ? "上午":"下午";
//           timeStr =time.year.toString()+"年"+time.month.toString()+"月"+time.day.toString()+"日"+str+time.hour.toString()+"时"+time.minute.toString()+"分";
//           }else{
//             timeStr =time.year.toString()+"年"+time.month.toString()+"月"+time.day.toString()+"日";
//           }
// //          print(formatDate(DateTime(1989, 02, 21), [yyyy, '-', mm, '-', dd]));
//              clickCallback(timeStr,picker.adapter.text);

//           }

//           );

//         }

}
